<template>
  <div class="app-container">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="所属公司">
        <el-select v-model="gongsiSel1" @change="initData" placeholder="所属公司">
          <el-option v-for="val in gongsiList" :key="val.id" :label="val.name" :value="val.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="handleAddRole">
      新增
    </el-button>

    <el-table :data="dataList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" prop="name" label="分公司名称" width="220">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="分公司地址">
        <template slot-scope="scope">
          {{ scope.row.address }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          {{ timeChange(scope.row.created) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="Operations">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑分公司信息':'新增分公司'">
      <el-form :model="role" :rules="rules" label-width="160px" label-position="left">
        <el-form-item label="所属公司" prop="tenantId">
          <el-select v-model="role.parentId" placeholder="所属公司">
            <el-option v-for="val in gongsiList" :key="val.id" :label="val.name" :value="val.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分公司名称" prop="name">
          <el-input v-model="role.name" placeholder="请输入分公司名称" />
        </el-form-item>
        <el-form-item label="分公司地址" prop="address">
          <el-input v-model="role.address" placeholder="请输入分公司地址" />
        </el-form-item>
        <el-form-item label="省市区" prop="shengshiqu">
          <el-cascader
            :options="shengshiquList"
            :clearable="true"
            size="mini"
            ref="cascader"
            @change="handleItemChange"
            @active-item-change="handleItemChange"
            :change-on-select="changeOnSelect"
            :props="{children: 'child',label: 'name',value: 'main'}"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="分成比例" prop="dividePercentage">
          <el-input v-model="role.dividePercentage" placeholder="请输入分成比例" />
        </el-form-item>
        <el-form-item label="支付宝商户号" prop="alipayMerchantAccount">
          <el-input v-model="role.alipayMerchantAccount" placeholder="请输入支付宝商户号" />
        </el-form-item>
        <el-form-item label="微信商户号" prop="wechatMerchantAccount">
          <el-input v-model="role.wechatMerchantAccount" placeholder="请输入微信商户号" />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">
          取消
        </el-button>
        <el-button type="primary" @click="confirmRole">
          确定
        </el-button>
      </div>
    </el-dialog>
    <!-- <Pagination :total="total" :page="page" @pagination="pagination" /> -->
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import Pagination from '@/components/Pagination/index'
import { getBranchId, postBranch, deleteBranch, getBranch, putBranch } from '@/api/Branch'
import { listArea, codeArea } from '@/api/Area'

const defaultRole = {
  "type": 1,
  "parentId": "",
  "name": "",
  "address": "",
  "provinceCode": "",
  "cityCode": "",
  "regionCode": "",
  "dividePercentage": 0,
  "wechatMerchantAccount": "",
  "alipayMerchantAccount": ""
}

export default {
  props:{
    // 如果该值为false 则只能选择最后一级 
    // 如果该值为true 则可以选择任意层级
    	changeOnSelect:{
			default:false
		}
  },
  data() {
    return {
      role: Object.assign({}, defaultRole),
      routes: [],
      dataList: [],
      dialogVisible: false,
      dialogType: 'new',
      shengshiquList:[],
      gongsiList:[],
      gongsiSel1: '',
      rules: {
        name: [
          { required: true, message: '请输入分公司名称' },
        ],
        parentId: [
          { required: true, message: '请选择所属公司' },
        ],
        shengshiqu: [
          { required: true, message: '请选择省市区' },
        ],
      },
      total: 10,
      page: 0,
    }
  },
  computed: {  },
  components: { Pagination },
  mounted() {
    this.gongsiList = JSON.parse(localStorage.getItem('companyList'));
    this.gongsiSel1 = this.gongsiList[0].id;
    this.initData();
    this.areaList();
  },
  methods: {
    //列表
    initData(){
      getBranch(this.gongsiSel1).then((res)=>{
        this.dataList = res.result;
      })
    }, 
    //时间格式转化
    timeChange(UTCDateString) {
      if (!UTCDateString) {
        return '-';
      }
      function formatFunc(str) {
        return str > 9 ? str : '0' + str
      }
      var date2 = new Date(UTCDateString);
      console.log('时间', date2)
      var year = date2.getFullYear();
      var mon = formatFunc(date2.getMonth() + 1);
      var day = formatFunc(date2.getDate());
      var hour = date2.getHours();
      var noon = hour >= 12 ? 'PM' : 'AM'; // 判断是上午还是下午
      hour = hour >= 12 ? hour - 12 : hour; // 12小时制
      hour = formatFunc(hour);
      var min = formatFunc(date2.getMinutes());
      var sec = formatFunc(date2.getSeconds());
      var dateStr = year + '-' + mon + '-' + day + ' ' + hour + ':' + min + ':' + sec;
      return dateStr;
    },   
    //省
    areaList(){
      codeArea('100000').then((res)=>{
        console.log(res)
        this.shengshiquList = res.result;
        this.shengshiquList.map((item, index) => {
          for (let k in item) {
            if (!item[k]) {
              delete item[k]
            }
          }
          // 先让数据变成父级
          item.child = []
          // 手动创建字段表明当前索引 假设arrIndex值为'1-2-3' 即为options[1].child[2].child[3]
          item.arrIndex = index + ''
          // 将当前数据转成字符串放入对象里 当做value值
          item.main = JSON.stringify(item)
        })
      })
    },
    handleItemChange (val) {
      // 因为允许选择任意级,所以在向下选择时,会出现选择多个的情况,造成选中的合并成了一个数组,我这里只让他选择到第三层,页面上最多只会出现选择三个,如果超出了,直接return出去 不需要再动态加载下去了
      if (val.length > 2) return
      //开门见山的说,每选中一个选项,相当于将本条数据push到val里,所以索引为val.length - 1的那一项必然是当前点击的那一项,哇 我他娘的可真是才思敏捷啊 
      val = JSON.parse(val[val.length - 1])
      if(val.length == 3){
        this.role.provinceCode = val[0].code;
        this.role.cityCode = val[1].code;
        this.role.regionCode = val[2].code;
      }
      //发送请求,是不是觉得和初始化用的同一个接口,然后还分两个事件有点冗余?写代码不累啊!
      codeArea(val.code).then(res => {
        let data = res.result
        //是不是有点迷糊 arrIndex哪来的?这玩意就是手动塞进去的索引
        let arrIndex = val.arrIndex
        data.map((item, index) => {
          // 手动创建字段表明当前索引 假设arrIndex值为'1-2-3' 即为options[1].child[2].child[3]
          item.arrIndex = arrIndex + '-' + index
          // 将当前数据转成字符串放入对象里 当做value值
          item.main = JSON.stringify(item)
          // 判断是否是第三层及以上
          if (item.arrIndex.split('-').length < 3) {
            item.child = []
          }
        })
        // 根据父元素的arrIndex判断塞到哪个父元素下
        arrIndex = arrIndex.split('-')
        // 首项键不是child 和for循环里区别开
        let a = this.shengshiquList[arrIndex[0]]
        for (let i = 1; i < arrIndex.length; i++) {
          a = a['child'][arrIndex[i]]
        }
        // 方法丑是丑了点...不过...真香
        this.$delete(a, 'child');
        this.$set(a, 'child', data)
      })
    },
    handleAddRole() {
      this.role = Object.assign({}, defaultRole)
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      getBranchId(scope.row.id).then((res)=>{
        let obj = res.result;
        delete obj.created;
        delete obj.modified;
        this.dialogVisible = true
        this.role = obj;
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('确认删除?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          deleteBranch(row.id).then((res)=>{
            console.log(res)
            this.initData();
            this.dialogVisible = false
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        })
        .catch(err => { console.error(err) })
    },
    async confirmRole() {
      if(this.dialogType==='edit'){
        putBranch(this.role.id,this.role).then((res)=>{
          console.log(res)
          this.initData();
          this.dialogVisible = false
          this.$message({
            type: 'success',
            message: '编辑成功!'
          })
        })
      }else{
        if(this.role.regionCode == ''){
          this.$message({
            type: 'error',
            message: '请选择省市区!'
          })
          return
        }
        postBranch(this.role).then((res)=>{
          console.log(res)
          this.initData();
          this.dialogVisible = false
          this.$message({
            type: 'success',
            message: '创建成功!'
          })
        })
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
